package com.example.demo.leetcode.top100;

import java.util.Stack;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _71字符串解码
 * @description
 * @date 2023/06/25 10:15
 * <p>
 * ******************************************************
 */
public class _71字符串解码 {

    public String decodeString(String s) {
        Stack<String> stack = new Stack<>();
        StringBuilder builder = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (c == ']') {
                StringBuilder unit = new StringBuilder();
                while (!"[".equals(stack.peek())) {
                    unit.append(stack.pop());
                }
//                unit.reverse();
                stack.pop();
                StringBuilder times = new StringBuilder();
                while (!stack.isEmpty() && stack.peek().charAt(0) >= 48 && stack.peek().charAt(0) <= 57) {
                    times.insert(0, stack.pop());
                }
                int n = Integer.parseInt(times.toString());
                StringBuilder item = new StringBuilder();
                for (int i = 0; i < n; i++) {
                    item.append(unit);
                }
                stack.push(item.toString());
            } else {
                stack.push(String.valueOf(c));
            }
        }
        while (!stack.isEmpty()) {
            builder.append(stack.pop());
        }
        return builder.reverse().toString();
    }


    public static void main(String[] args) {
        _71字符串解码 s = new _71字符串解码();
        System.out.println(s.decodeString("3[z]2[2[y]pq4[2[jk]e1[f]]]ef"));
    }

}
